package com.xw.musicplayer;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.xw.musicplayer.bean.Music;
import com.xw.musicplayer.engine.PlayerFactory;
import com.xw.musicplayer.listener.IMediaPlayer;
import com.xw.musicplayer.listener.OnBufferingListener;
import com.xw.musicplayer.listener.OnMusicChangeListener;
import com.xw.musicplayer.listener.OnStatusChangeListener;
import com.xw.musicplayer.utils.NetworkUtils;
import com.xw.musicplayer.utils.PlayStatus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class PlayController implements
        IMediaPlayer.OnPreparedListener,
        IMediaPlayer.OnCompletionListener,
        IMediaPlayer.OnBufferingUpdateListener,
        IMediaPlayer.OnErrorListener,
        IMediaPlayer.OnInfoListener,
        IMediaPlayer.OnSeekCompleteListener {

    private int mState = PlayStatus.STATE_IDLE;
    private String mMusicListId;

    private CopyOnWriteArrayList<Music> mMusicList = new CopyOnWriteArrayList<>();
    private List<OnStatusChangeListener> mOnStatusChangeListenerList = new ArrayList<>();
    private List<OnMusicChangeListener> mOnMusicChangeListenerList = new ArrayList<>();
    private List<OnBufferingListener> mOnBufferingListenerList = new ArrayList<>();

    private IMediaPlayer mPlayer;
    private Context mContext;

    private int mPlayIndex;
    private int mLastPlayIndex = -1;
    private int mBufferedPercentage;

    public void init(Context context) {
        if (mPlayer == null) {
            this.mContext = context;
            mPlayer = PlayerFactory.getPlayManager();
            mPlayer.init(context);

            //资源加载
            mPlayer.setOnPreparedListener(this);
            //播放完成
            mPlayer.setOnCompletionListener(this);
            //缓冲百分比事件
            mPlayer.setOnBufferingUpdateListener(this);
            //错误事件
            mPlayer.setOnErrorListener(this);
            //提示信息事件
            mPlayer.setOnInfoListener(this);
            //seek操作完成
            mPlayer.setOnSeekCompleteListener(this);

        }
    }

    /**
     * 设置播放队列.
     */
    public void setmMusicList(String musicListId,List<Music> musicList) {
        mMusicListId = musicListId;
        mPlayIndex = 0;
        mLastPlayIndex = -1;
        reset();
        mMusicList.clear();
        mMusicList.addAll(musicList);
    }

    /**
     * 获取播放列表
     */
    public List<Music> getMusicList() {
        return mMusicList;
    }

    /**
     * 获取某个下标的音乐
     */
    public Music getMusic(int position) {
        if (position >= 0 && position < mMusicList.size()) {
            return mMusicList.get(position);
        } else {
            return null;
        }
    }

    public String getMusicListId() {
        return mMusicListId;
    }

    /**
     * 获取列表总数.
     */
    public int getMusicCount() {
        return mMusicList.size();
    }

    /**
     * 获取正在播放的音乐索引.
     */
    public int getPlayIndex() {
        return mPlayIndex;
    }

    /**
     * 获取当前正在播放的音乐.
     */
    public Music getCurrent() {
        return getMusic(mPlayIndex);
    }

    private void changeState(int newState) {
        mState = newState;
        for (OnStatusChangeListener listener : mOnStatusChangeListenerList) {
            listener.onStatusChange(newState);
        }
    }

    /**
     * 是否是合法的音频信息.
     */
    private boolean available(Music music) {
        return music != null && !TextUtils.isEmpty(music.pathUrl);
    }


    @Override
    public void onPrepared(IMediaPlayer mp) {
        changeState(PlayStatus.STATE_PLAYING);
        mBufferedPercentage = 0;
        mPlayer.start();
    }

    @Override
    public void onCompletion(IMediaPlayer mp) {
        next();
    }

    @Override
    public void onBufferingUpdate(IMediaPlayer mp, int percent) {
        updateBuffering(percent);
    }

    @Override
    public void onSeekComplete(IMediaPlayer mp) {

    }

    @Override
    public boolean onError(IMediaPlayer mp, int what, int extra) {
        if (BuildConfig.DEBUG) {
            Log.d("info","播放错误=what=" + what + "=extra=" + extra);
        }
        return false;
    }

    @Override
    public boolean onInfo(IMediaPlayer mp, int what, int extra) {
        if (BuildConfig.DEBUG) {
            Log.d("info","onInfo=what=" + what + "=extra=" + extra);
        }

        if (what == IMediaPlayer.MEDIA_INFO_BUFFERING_START) {
            //内核临时缓冲暂停播放开始缓冲
            notifyBuffing(true);
        } else if (what == IMediaPlayer.MEDIA_INFO_BUFFERING_END) {
            //内核临时缓冲成功开始播放
            notifyBuffing(false);
        }

        return false;
    }

    private void notifyBuffing(boolean start) {
        if (start) {
            for (OnBufferingListener listener : mOnBufferingListenerList) {
                listener.onBufferingStart();
            }
        } else {
            for (OnBufferingListener listener : mOnBufferingListenerList) {
                listener.onBufferingEnd();
            }
        }
    }

    /**
     * 更新缓冲进度.
     */
    private void updateBuffering(int percent) {
        mBufferedPercentage = percent;
    }

    /**
     * 一个音频播放完成后,如果可以则自动播放下一曲.
     */
    private void next() {
        mPlayIndex++;
        if (mPlayIndex >= mMusicList.size()) {
            reset();
            mPlayIndex = 0;
            return;
        }

        if (!playIndex()) {
            next();
        }
    }

    public void reset() {
        changeState(PlayStatus.STATE_IDLE);
        mPlayer.reset();
    }

    public void setSeek(int millis) {
        mPlayer.seekTo(millis);
    }

    public long getCurrentPosition() {
        return mPlayer.getCurrentPosition();
    }

    public long getDuration() {
        return mPlayer.getDuration();
    }

    public int getBufferedPercentage() {
        return mBufferedPercentage;
    }

    public boolean isPlaying() {
        return mState == PlayStatus.STATE_PLAYING || mState == PlayStatus.STATE_PREPARING;
    }

    /**
     * 销毁资源后需要重新实例化.
     */
    public void destroy() {
        changeState(PlayStatus.STATE_RELEASE);
        if (mPlayer != null) {
            mPlayer.release();
        }
        mOnStatusChangeListenerList.clear();
        mOnMusicChangeListenerList.clear();
        mOnBufferingListenerList.clear();
//        MusicPlayer.getInstance().removeFloatWindow();
    }

    public void play() {
        if (mMusicList.isEmpty()) {
            return;
        }

        switch (mState) {

            case PlayStatus.STATE_PLAYING:
            case PlayStatus.STATE_PREPARING:
                //正在播放或者正在准备
                break;

            case PlayStatus.STATE_PAUSE:
                changeState(PlayStatus.STATE_PLAYING);
                mPlayer.start();
                break;

            case PlayStatus.STATE_IDLE:
                if (!playIndex()) {
                    Log.d("info","==PlayController=启动失败=");
                    //没有启动成功,自动播放下一曲
                    next();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 下一首
     */
    public void playNext() {
        if (mPlayIndex >= mMusicList.size() - 1) {
            playIndex(0);
        } else {
            next();
        }
    }

    /**
     * 上一首
     */
    public void playPrevois() {
        if (mPlayIndex <= 0) {
            playIndex(mMusicList.size() - 1);
        } else {
            playIndex(mPlayIndex - 1);
        }
    }

    public void pause() {
        if (mState == PlayStatus.STATE_PLAYING || mState == PlayStatus.STATE_PREPARING) {
            changeState(PlayStatus.STATE_PAUSE);
            mPlayer.pause();
        }
    }

    public void playIndex(int position) {
        if (position < 0 || position >= mMusicList.size()) {
            return;
        }

        if (position != mPlayIndex) {
            reset();
            mPlayIndex = position;
        }

        play();
    }

    /**
     * 播放某个url形式的音频.
     */
    private boolean playIndex() {
        String url;

        Music music = getMusic(mPlayIndex);
        if (available(music)) {
            url = music.pathUrl;
        } else {
            return false;
        }

        if (!NetworkUtils.isConnected(mContext)) {
            reset();
            return false;
        }

        return playReal(url);
    }

    /**
     * 通过文件路径或者网络路径播放音视频
     */
    private boolean playReal(String url) {
        try {
            if (mLastPlayIndex != mPlayIndex) {
                for (OnMusicChangeListener listener : mOnMusicChangeListenerList) {
                    listener.onMusicChange(mPlayIndex,mLastPlayIndex);
                }

                mLastPlayIndex = mPlayIndex;
                mPlayer.reset();

                mPlayer.setDataSource(url);
                mPlayer.prepareAsync();
                changeState(PlayStatus.STATE_PREPARING);
            }
        } catch (Exception e) {
            e.printStackTrace();
            reset();
            return false;
        }

        return true;
    }

    public void registerStatusChangeListener(OnStatusChangeListener listener) {
        if (!mOnStatusChangeListenerList.contains(listener)) {
            mOnStatusChangeListenerList.add(listener);
        }
    }

    public void unregisterStatusChangeListener(OnStatusChangeListener listener) {
        mOnStatusChangeListenerList.remove(listener);
    }

    public void registerMusicChangeListener(OnMusicChangeListener listener) {
        if (!mOnMusicChangeListenerList.contains(listener)) {
            mOnMusicChangeListenerList.add(listener);
        }
    }

    public void unregisterMusicChangeListener(OnMusicChangeListener listener) {
        mOnMusicChangeListenerList.remove(listener);
    }

    public void registerBuffingListener(OnBufferingListener listener) {
        if (!mOnBufferingListenerList.contains(listener)) {
            mOnBufferingListenerList.add(listener);
        }
    }

    public void unregisterBuffingListener(OnBufferingListener listener) {
        mOnBufferingListenerList.remove(listener);
    }


}
